package com.neusoft.hifly.lock.strategy.impl;

import org.apache.commons.lang3.StringUtils;
import org.redisson.config.Config;

import com.neusoft.hifly.lock.config.RedissonConfig;
import com.neusoft.hifly.lock.constant.GlobalConstant;
import com.neusoft.hifly.lock.strategy.RedissonConfigService;
import com.neusoft.hifly.lock.utils.Log;

/**
 * 集群方式Redisson部署 地址格式：
 * <p>
 * cluster方式至少6个节点(3主3从，3主做sharding，3从用来保证主宕机后可以高可用)
 * <p>
 * 格式为: 127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384
 */
public class ClusterConfigImpl implements RedissonConfigService {
	/**
	 * 根据不同的Redis配置策略创建对应的Config
	 *
	 * @param redissonProperties
	 *            redisson配置
	 * @return Config
	 */
	@Override
	public Config createRedissonConfig(final RedissonConfig redissonProperties) {
		final Config config = new Config();
		try {
			final String address = redissonProperties.getAddress();
			final String password = redissonProperties.getPassword();
			final String[] addrTokens = address.split(",");
			//设置cluster节点的服务IP和端口
			for (final String addrToken : addrTokens) {
				config.useClusterServers()
						.addNodeAddress(GlobalConstant.REDIS_CONNECTION_PREFIX.getConstantValue() + addrToken);
				if (StringUtils.isNotBlank(password)) {
					config.useClusterServers().setPassword(password);
				}
			}
			Log.info("初始化[集群部署]方式Config,redisAddress:" + address);
		} catch (final Exception e) {
			Log.info("集群部署 Redisson init error", e);
			e.printStackTrace();
		}
		return config;
	}
}
